package com.shop.item.api.controller;


import com.alibaba.fastjson.JSON;
import com.shop.common.entity.user.UserBase;
import com.shop.common.model.InputBean;
import com.shop.common.model.ServiceBean;
import com.shop.common.model.param.item.ItemBaseInput;
import com.shop.common.model.param.item.ItemDetailsInput;
import com.shop.common.model.result.item.ItemBaseOutput;
import com.shop.common.tmpl.BaseController;
import com.shop.common.util.RedisUtil;
import com.shop.common.util.state.ResultCode;
import com.shop.common.util.SessionUtils;
import com.shop.common.util.excption.UserNotFoundException;
import com.shop.item.api.model.Item;
import com.shop.item.api.service.IItemEditService;
import com.shop.item.api.service.IItemService;
import com.shop.item.api.service.ISolrService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/item/")
@CrossOrigin
/**
 * @Author zhoulk
 * @Description //TODO 
 * @Date 14:00 2019/3/22
 *
 **/
public class ItemController extends BaseController {
    static final Logger logger = LoggerFactory.getLogger(ItemController.class);

    @Autowired
    IItemService itemService;
    @Autowired
    IItemEditService itemEditService;
    @Autowired
    RedisUtil REDIS_UTIL;
    @Autowired
    SessionUtils SESSION_UTILS;
    @Autowired
    ISolrService solrService;


    /**
     * @return java.lang.String
     * @Author zhoulk
     * @Description //TODO 新建基本商品
     * @Date 14:22 2019/1/17
     * @Param [itemSelect, request]
     * @errorCode //TODO
     **/
    @PostMapping("/base")
    public String apiAddItemBase(@RequestBody ItemBaseInput itemBase, HttpServletRequest request) throws UserNotFoundException {
        UserBase userBase = SESSION_UTILS.GET_USER(request);
        itemBase.setUserId(userBase.getUserId());
        itemBase.setMchtType(userBase.getType());
        InputBean<ItemBaseInput> inputBean = newParamMode(itemBase);
        ServiceBean<Integer> serviceBean = itemService.addItemBase(inputBean);
        if (serviceBean.isSuccess()) {
            Integer itemId = serviceBean.getData();
            Map<String, String> map = new HashMap<>();
            map.put("itemId", itemId.toString());
            return returnJSON(ResultCode.SUCCESS.value(), "创建商品成功", map);
        }
        return returnSvc(serviceBean);
    }

    /**
     * @return java.lang.String
     * @Author zhoulk
     * @Description //TODO 更新商品基本信息
     * @Date 16:14 2019/3/11
     * @Param [itemBase, request]
     * @errorCode //TODO
     **/
    @PutMapping("/updateBase")
    public String serviceUpdateBase(@RequestBody ItemBaseInput itemBase, HttpServletRequest request) {
        InputBean<ItemBaseInput> inputBean = newParamMode(itemBase);
        ServiceBean<String> serviceBean = itemEditService.updateItemBase(inputBean);
        if (serviceBean.isSuccess()) {
            return returnSuccess();
        }
        return returnFailed(serviceBean.getMsg());
    }

    /**
     * @return java.lang.String
     * @Author zhoulk
     * @Description //TODO 新增商品详情
     * @Date 16:18 2019/3/11
     * @Param [ItemDetails, request]
     * @errorCode //TODO
     **/
    @PostMapping("/details")
    public String apiAddDetails(@RequestBody ItemDetailsInput ItemDetails, HttpServletRequest request) {
        String token = getToken(request);
        InputBean<ItemDetailsInput> inputBean = newParamMode(ItemDetails);
        inputBean.setToken(token);
        ServiceBean<Integer> serviceBean = itemService.addItemDetails(inputBean);
        if (serviceBean.isSuccess()) {
            return returnSuccess();
        }
        return returnFailed();
    }

    /**
     * @return java.lang.String
     * @Author zhoulk
     * @Description //TODO 更新商品details
     * @Date 16:18 2019/3/11
     * @Param [ItemDetails, request]
     * @errorCode //TODO
     **/
    @PutMapping("/details")
    public String apiUpdateDetails(@RequestBody ItemDetailsInput ItemDetails, HttpServletRequest request) {
        String token = getToken(request);
        InputBean<ItemDetailsInput> inputBean = newParamMode(ItemDetails);
        inputBean.setToken(token);
        ServiceBean<String> serviceBean = itemEditService.updateItemDetails(inputBean);
        if (serviceBean.isSuccess()) {
            return returnSuccess();
        }
        return returnFailed(serviceBean.getMsg());
    }

    /**
     * @return java.lang.String
     * @Author zhoulk
     * @Description //TODO 删除商品
     * @Date 16:17 2019/3/11
     * @Param [itemIdStr]
     * @errorCode //TODO
     **/
    @DeleteMapping("/item")
    public String apiDeleteItem(String itemIdStr, HttpServletRequest request) throws UserNotFoundException {
        Integer userId = SESSION_UTILS.USER_ID(request);
        if (StringUtils.isBlank(itemIdStr)) {
            return returnFailed();
        }
        Integer itemId = Integer.valueOf(itemIdStr);
        InputBean<Integer> inputBean = newParamMode(itemId);
        inputBean.setUserId(userId);
        ServiceBean serviceBean = itemService.deleteItemByItemId(inputBean);
        if (serviceBean.isSuccess()) {
            return returnSuccess();
        }
        return returnFailed();
    }

    /**
     * @return java.lang.String
     * @Author zhoulk
     * @Description //TODO 后台查询商品信息
     * @Date 16:19 2019/3/11
     * @Param [item, request]
     * @errorCode //TODO
     **/
    @GetMapping("/item")
    public String apiSelectItem(ItemBaseInput item, HttpServletRequest request) throws UserNotFoundException {
        UserBase userBase = SESSION_UTILS.GET_USER(request);
        item.setUserId(userBase.getUserId());
        InputBean<ItemBaseInput> inputBean = new InputBean<>();
        inputBean.setParam(item);
        ServiceBean serviceBean = itemService.selectItem(inputBean);
        if (!serviceBean.isSuccess()) {
            returnFailed();
        }
        return returnJSON(ResultCode.SUCCESS.value(), "", serviceBean.getData());
    }

    /**
     * @return java.lang.String
     * @Author zhoulk
     * @Description //TODO 查询商品列表
     * @Date 16:19 2019/3/11
     * @Param [item, request]
     * @errorCode //TODO
     **/
    @GetMapping("/items")
    public String apiSelectItems(ItemBaseInput item, HttpServletRequest request) throws UserNotFoundException {
        Integer userId = SESSION_UTILS.USER_ID(request);
        item.setUserId(userId);
        InputBean<ItemBaseInput> inputBean = new InputBean<>();
        inputBean.setParam(item);
        List<Item> itemList = itemService.selectItemList(inputBean).getData();
        return returnJSON(ResultCode.SUCCESS.value(), "", itemList);
    }

    /**
     * @return java.lang.String
     * @Author zhoulk
     * @Description //TODO 分页查询商品列表
     * @Date 16:19 2019/3/11
     * @Param [item, request]
     * @errorCode //TODO
     **/
    @GetMapping("/items4P")
    public String apiSelectItems4P(ItemBaseInput item, HttpServletRequest request) throws UserNotFoundException {
        Integer userId = SESSION_UTILS.USER_ID(request);
        item.setUserId(userId);
        InputBean<ItemBaseInput> inputBean = new InputBean<>();
        inputBean.setIndex(item.getPageIndex());
        inputBean.setPageSize(item.getPageSize());
        inputBean.setParam(item);
        Map<String, Object> map = itemService.selectItemList4P(inputBean).getData();
        return JSON.toJSONString(map);
    }

    /**
     * @return java.lang.String
     * @Author zhoulk
     * @Description //TODO 修改商品状态
     * @Date 16:20 2019/3/11
     * @Param [item, request, response]
     * @errorCode //TODO
     **/
    @PutMapping("/itemStatus")
    public String apiMdfItemStatus(@RequestBody ItemBaseInput item, HttpServletRequest request, HttpServletResponse response) {
        InputBean<ItemBaseInput> inputBean = new InputBean<>();
        inputBean.setParam(item);
        ServiceBean serviceBean = itemService.mdfItemStatus(inputBean);
        if (serviceBean.isSuccess()) {
            return returnSuccess("成功");
        }
        return returnFailed();
    }

    /**
     * @return java.lang.String
     * @Author zhoulk
     * @Description //TODO 前台浏览商品信息
     * @Date 16:25 2019/3/11
     * @Param [itemId, request]
     * @errorCode //TODO
     **/
    @GetMapping("/browser")
    public String getItem(String itemId, HttpServletRequest request) throws UserNotFoundException {
        Integer userId = SESSION_UTILS.USER_ID(request);
        if (StringUtils.isBlank(itemId)) {
            return returnFailed("商品id错误");
        }
        ItemBaseInput itemBase = new ItemBaseInput();
        itemBase.setItemId(Integer.valueOf(itemId));
        InputBean<ItemBaseInput> inputInputBean = new InputBean<>(itemBase);
        if (userId != null) {
            logger.info("用户【" + userId + "】查看商品【" + itemId + "】");
            inputInputBean.setUserId(userId);
        }
        ServiceBean<ItemBaseOutput> serviceBean = itemService.browserItem(inputInputBean);
        if (!serviceBean.isSuccess()) {
            return returnFailed(serviceBean.getMsg());
        }
        return returnData(serviceBean.getData());
    }

    @GetMapping("/searchItemList")
    public String queryItemListForSolr(ItemBaseInput itemBaseInput, String sortkey, Integer index, Integer pageSize) {
        InputBean<ItemBaseInput> inputBean = new InputBean<>(itemBaseInput);
        inputBean.setIndex(index);
        inputBean.setPageSize(pageSize);
        List<String> sort = new ArrayList<>();
        switch (sortkey) {
            case "1":
                sort.add("createTime");
                break;
            case "2":
                sort.add("sellingPrice");
                break;
            case "3":
                sort.add("hotcode");
                break;
        }
        ServiceBean<List<ItemBaseOutput>> serviceBean = solrService.selectItemList(inputBean, sort);
        Map<String, Object> map = new HashMap<>();
        map.put("total", serviceBean.getMaxSize());
        map.put("rows", serviceBean.getData());
        return returnData(map);
    }

    @GetMapping("/fullImport")
    public String fullImportSolr() {
        return returnData(solrService.fullImport());
    }

    @GetMapping("/initHome")
    public String initHomePage() {
        InputBean<ItemBaseInput> inputBean = new InputBean<>();
        inputBean.setIndex(1);
        inputBean.setPageSize(12);
        List<String> sort = new ArrayList<>();
        sort.add("hotcode");
        ServiceBean<List<ItemBaseOutput>> serviceBean = solrService.selectItemList(inputBean, sort);
        Map<String, List<ItemBaseOutput>> map = new HashMap<>();
        map.put("hot", serviceBean.getData());
        sort = new ArrayList<>();
        serviceBean = solrService.selectItemList(inputBean, sort);
        map.put("new", serviceBean.getData());
        return returnData(map);
    }

}
